import Vue from 'vue'
import store from '../store'
import axios from 'axios'
import {Message, Loading} from 'element-ui'
import api from '../api'
import cookie from '../utils/cookie'

Vue.mixin({
  methods: {
    request: function (url, params, fn, cfg) {
      let that = this;
      let loadingInstance1
      let config = cfg || {}
      if (!config.hideLoading) {
        loadingInstance1 = Loading.service({fullscreen: true})
      }
      let form = new FormData(); // 创建form对象
      form.append('inCharset', 'utf-8');
      form.append('token', cookie.get("token"));
      for (var key in params) {
        form.append(key, params[key]);
      }
      let _config = {
        headers: {'Content-Type': 'multipart/form-data'}
      };  //添加请求头
      axios.post(url, form, _config).then(function (response) {
        loadingInstance1.close()
        let resp = response.data
        if (resp.code == -1) { // 没有权限的访问
          that.$router.replace({name: 'login'})
        } else {
          fn && fn(resp);
        }
      }).catch(function (error) {
        console.log("error:", error)
        Message('数据加载异常！')
      });
    },
    syncRequest: function (url, data, fn) {
      var xhr = new XMLHttpRequest()
      xhr.open("POST", url, false)
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  // 添加http头，发送信息至服务器时内容编码类型
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {  // 304未修改
          fn.call(this, xhr.responseText)
        }
      };
      xhr.send(data)
    },
    getUser: function (fn) {
      var that = this
      that.request(api.get_user_by_token, {}, function (json) {
        if (json.code == 0) {
          let user = json.data;
          fn && fn(user)
        } else {
          that.$router.push({name: 'login'})
        }
      })
    },
    getBasedata: function (fn) {
      var that = this
      if (that.basedata) {
        fn && fn(that.basedata)
      } else {
        that.request(api.get_basedata, {}, function (json) {
          if (json.code === 0) {
            that.basedata = json.data
            fn && fn(that.basedata)
          }
        })
      }
    },
    // resolve the transition state before route switch
    goforward(route) {
      store.commit('transition/setTransition', 'turn-on')
      return route
    },
    backward() {
      store.commit('transition/setTransition', 'turn-off')
    }
  }
})
